package com.gwd.task.middles;

import com.gwd.task.exception.UnAuthorizationException;
import com.gwd.task.untils.JwtUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author zhiyongming
 * @date 2020/11/12 17:37
 */
public class LoginInterceptor implements HandlerInterceptor {

    @Value("${config.verified}")
    private final Boolean verified = true;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        String authorization = request.getHeader("Authorization");
        if (authorization==null) {
            if (!verified) {
                return true;
            }
            throw new UnAuthorizationException();
        }
        Long verity = JwtUtil.verity(authorization);
        if (verity == 0L) {
            if (!verified) {
                return true;
            }
            throw new UnAuthorizationException();
        }
        request.setAttribute("userId", verity);
        return true;
    }
}
